package cn.ljy.authority.config.security.user;

import cn.ljy.authority.model.dto.SysUserAuthority;
import cn.ljy.authority.service.SysUserTokenService;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 处理后台管理员登录验证成功后的类
 */
@Slf4j
@Component
public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        SysUserAuthority userAuthority = (SysUserAuthority) authentication.getPrincipal();
        //登录成功后生成token，并将token存入redis
        String token= sysUserTokenService.saveUserToken(userAuthority);
        //将token存入token
        HashMap<String, String> map = new HashMap<>();
        map.put("accessToken",token);
        //ResponseUtil.responseJson(response,ResultCode.SUCCESS.getCode(),"登录成功",map);
        ResponseUtil.responseJson(response, ResponseData.success(map));
    }
}
